package com.dy.yunying.biz.controller.hongbao;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dy.yunying.api.dto.hongbao.HbReceivingRecordDto;
import com.dy.yunying.api.entity.GameRole;
import com.dy.yunying.api.entity.WanRechargeOrder;
import com.dy.yunying.api.entity.WanUser;
import com.dy.yunying.api.entity.hongbao.HbActivityRoleInfo;
import com.dy.yunying.api.entity.hongbao.HbReceivingRecord;
import com.dy.yunying.api.entity.raffle.RaffleReceiveRecord;
import com.dy.yunying.api.enums.HbReceivStatusEnum;
import com.dy.yunying.api.enums.HbRedpackTypeEnum;
import com.dy.yunying.api.vo.hongbao.HbReceivingRecordExportVo;
import com.dy.yunying.api.vo.hongbao.HbReceivingRecordVo;
import com.dy.yunying.api.vo.hongbao.HbWithdrawRecordDetailVo;
import com.dy.yunying.biz.service.hongbao.HbActivityRoleInfoService;
import com.dy.yunying.biz.service.hongbao.HbReceivingRecordService;
import com.dy.yunying.biz.service.manage.GameRoleService;
import com.dy.yunying.biz.service.manage.WanRechargeOrderService;
import com.dy.yunying.biz.service.manage.WanUserService;
import com.dy.yunying.biz.service.raffle.RaffleReceiveRecordService;
import com.dy.yunying.biz.utils.DateUtils;
import com.dy.yunying.biz.utils.ExportUtils;
import com.dy.yunying.biz.utils.MapUtils;
import com.google.common.collect.Lists;
import com.pig4cloud.pig.api.util.NoRepeatSubmit;
import com.pig4cloud.pig.common.core.exception.BusinessException;
import com.pig4cloud.pig.common.core.util.R;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 奖品领取记录
 * @author  chenxiang
 * @version  2021-10-27 13:55:13
 * table: hb_receiving_record
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/receivingRecord")
@Slf4j
public class HbReceivingRecordController {

    private final HbReceivingRecordService hbReceivingRecordService;

	private final HbActivityRoleInfoService hbActivityRoleInfoService;

	private final GameRoleService gameRoleService;

	private final WanRechargeOrderService wanRechargeOrderService;

	private final WanUserService wanUserService;

	private final RaffleReceiveRecordService raffleReceiveRecordService;

	/**
	 * 领取记录列表
	 * @param vo
	 * @return
	 */
	@RequestMapping("/getPage")
	public R getPage(@RequestBody HbReceivingRecordVo vo){
		return hbReceivingRecordService.getPage(vo);
	}
	/**
	 * 礼包审核列表
	 * @param vo
	 * @return
	 */
	@RequestMapping("/getGiftVerifyPage")
	public R getGiftPage(@RequestBody HbReceivingRecordVo vo){
		vo.setObjectType("1");
		vo.setType("3");
		return hbReceivingRecordService.getPage(vo);
	}
	/**
	 * 审核礼品
	 * @param vo
	 * @return
	 */
	@RequestMapping("/verifyRecord")
	public R verifyRecord(@RequestBody HbReceivingRecordVo vo){
		if (StringUtils.isBlank(vo.getId())){
			return R.failed("主键ID不能为空");
		}
		if (StringUtils.isBlank(vo.getStatus())){
			return R.failed("状态不能为空");
		}
		if (StringUtils.equals("7",vo.getStatus())){
			if (StringUtils.isBlank(vo.getForbidReason())){
				return R.failed("驳回原因不能为空");
			}
		}
		return hbReceivingRecordService.verifyRecord(vo);
	}
	/**
	 * 发货 - 填写快递信息
	 * @param vo
	 * @return
	 */
	@RequestMapping("/deliverGoods")
	public R deliverGoods(@RequestBody HbReceivingRecordVo vo){
		if (StringUtils.isBlank(vo.getId())){
			return R.failed("主键ID不能为空");
		}
		if (StringUtils.isBlank(vo.getExpressName())){
			return R.failed("快递名称不能为空");
		}
		if (StringUtils.isBlank(vo.getExpressCode())){
			return R.failed("快递单号不能为空");
		}
		return hbReceivingRecordService.deliverGoods(vo);
	}



	/**
	 * 礼品审核数据导出
	 *
	 * @param vo
	 * @return
	 */
	@PostMapping("/export")
	public void export( @RequestBody HbReceivingRecordVo vo, HttpServletResponse response) {
		String sheetName = "礼品审核";
		try {
			List<HbReceivingRecordDto> list = hbReceivingRecordService.exportRecord(vo);
			List<HbReceivingRecordExportVo> hbReceivingRecordExportVoList= Lists.newArrayList();
			if(CollectionUtils.isNotEmpty(list)){
				list.forEach(s->{
					HbReceivingRecordExportVo hbReceivingRecordExportVo=new HbReceivingRecordExportVo();
					BeanUtils.copyProperties(s,hbReceivingRecordExportVo);
					hbReceivingRecordExportVo.setTypeName(HbRedpackTypeEnum.getName(s.getType().toString()));
					hbReceivingRecordExportVo.setStatusName(HbReceivStatusEnum.getName(s.getStatus().toString()));
					if (Objects.nonNull(s.getReceiveTime())){
						hbReceivingRecordExportVo.setReceiveTimeStr(DateUtils.dateToString(s.getReceiveTime(),DateUtils.YYYY_MM_DD_HH_MM_SS));
					}
					if (Objects.nonNull(s.getSendTime())){
						hbReceivingRecordExportVo.setSendTimeStr(DateUtils.dateToString(s.getSendTime(),DateUtils.YYYY_MM_DD_HH_MM_SS));
					}
					if (Objects.nonNull(s.getUpdateTime())){
						hbReceivingRecordExportVo.setUpdateTimeStr(DateUtils.dateToString(s.getUpdateTime(),DateUtils.YYYY_MM_DD_HH_MM_SS));
					}
					hbReceivingRecordExportVoList.add(hbReceivingRecordExportVo);
				});
			}
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			response.setCharacterEncoding("utf-8");
			String fileName = URLEncoder.encode("礼品审核-" + DateUtils.getCurrentTimeNoUnderline(), "UTF-8").replaceAll("\\+", "%20");
			response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
			response.setHeader("file-name", fileName);
			//设置excel宽度自适应
			ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();
			// 创建sheet并设置动态标题

			WriteSheet detailSheet = EasyExcel.writerSheet(0, sheetName).head(HbReceivingRecordExportVo.class).build();
			// 向sheet中写入数据，将值按照动态顺序进行处理后放入
			excelWriter.write((List<HbReceivingRecordExportVo>) hbReceivingRecordExportVoList,detailSheet);
			// 数据下载，完成后会自动关闭流
			excelWriter.finish();

		} catch (Exception e) {
			log.error("礼品审核数据数据导出异常：{}", e.getMessage());
			throw new BusinessException("礼品审核数据数据导出异常，请稍后重试");

		}


	}



	@ApiOperation(value = "礼品审核详情", notes = "礼品审核详情")
	@RequestMapping("/detail")
	@NoRepeatSubmit(lockTime = 3000)
	public R detail(HbReceivingRecordVo vo) {
		try {
			if (StringUtils.isBlank(vo.getId())) {
				return R.failed("记录ID不能为空");
			}
			Long id = Long.valueOf(vo.getId());
			Integer sourceType = StringUtils.isBlank(vo.getSourceType()) ? 1 : Integer.valueOf(vo.getSourceType());
			Long activityId;Long userId;String userName;Integer areaId;String roleId;Integer parentGameId;Integer gameId;
			if (4 == sourceType){
				RaffleReceiveRecord raffleReceiveRecord = raffleReceiveRecordService.getById(id);
				activityId = raffleReceiveRecord.getActivityId();
				userId = raffleReceiveRecord.getUserId();
				userName = raffleReceiveRecord.getUsername();
				areaId = Integer.valueOf(raffleReceiveRecord.getAreaId());
				roleId = raffleReceiveRecord.getRoleId();
				parentGameId = raffleReceiveRecord.getParentGameId().intValue();
				gameId = raffleReceiveRecord.getSubGameId().intValue();
			}else{
				HbReceivingRecord hbReceivingRecord = hbReceivingRecordService.getById(id);
				if (hbReceivingRecord == null) {
					return R.failed("该记录不存在");
				}
				activityId = hbReceivingRecord.getActivityId();
				userId = hbReceivingRecord.getUserId().longValue();
				userName = hbReceivingRecord.getUserName();
				areaId = hbReceivingRecord.getAreaId();
				roleId = hbReceivingRecord.getRoleId();
				parentGameId = hbReceivingRecord.getParentGameId();
				gameId = hbReceivingRecord.getGameId();
			}
			//收款账号、角色等级、角色累充()、注册时间、创角时间、最后付费时间、最后登录时间、登录IP
			//角色等级：当前等级
			//角色累充(元)：活动期间累计充值
			//注册时间：账号注册时间
			//创角时间：角色创建时间
			//最后付费时间：角色最后付费时间
			//最后登录时间：角色最后登录时间
			//登录IP：角色最后登录IP
			GameRole gameRole = gameRoleService.getOne(Wrappers.<GameRole>query()
					.lambda().eq(GameRole::getUserId, userId).eq(GameRole::getPgameId, parentGameId)
					.eq(GameRole::getAreaId, areaId).eq(GameRole::getRoleId, roleId).orderByDesc(GameRole::getRoleLevel).select(GameRole::getRoleLevel, GameRole::getCreateRoleTime, GameRole::getLoginTime, GameRole::getLoginIp).last("LIMIT 1"));

			HbActivityRoleInfo hbActivityRoleInfo = hbActivityRoleInfoService.getOne(Wrappers.<HbActivityRoleInfo>query()
					.lambda().eq(HbActivityRoleInfo::getActivityId, activityId)
					.eq(HbActivityRoleInfo::getSourceType, sourceType)
					.eq(HbActivityRoleInfo::getUserId, userId)
					.eq(HbActivityRoleInfo::getPgameId, parentGameId)
					.eq(HbActivityRoleInfo::getGameId, gameId)
					.eq(HbActivityRoleInfo::getAreaId, areaId)
					.eq(HbActivityRoleInfo::getRoleId, roleId)
					.orderByDesc(HbActivityRoleInfo::getTotalIncome)
					.select(HbActivityRoleInfo::getTotalRechargeAmount).last("LIMIT 1"));

			//
			WanRechargeOrder wanRechargeOrder = wanRechargeOrderService.getOne(Wrappers.<WanRechargeOrder>query()
					.lambda().eq(WanRechargeOrder::getAccount, userName).eq(WanRechargeOrder::getGameid, gameId)
					.eq(WanRechargeOrder::getAreaid, areaId).eq(WanRechargeOrder::getGrole, roleId).orderByDesc(WanRechargeOrder::getPaytime).select(WanRechargeOrder::getPaytime).last("LIMIT 1"));

			WanUser wanUser = wanUserService.getOne(Wrappers.<WanUser>query()
					.lambda().eq(WanUser::getUserid, userId).select(WanUser::getRegtime).last("LIMIT 1"));


			HbWithdrawRecordDetailVo detail = new HbWithdrawRecordDetailVo();
			detail.setCreateRoleTime(gameRole == null ? null : gameRole.getCreateRoleTime());
			detail.setLoginIp(gameRole == null ? null : gameRole.getLoginIp());
			detail.setLoginTime(gameRole == null ? null : gameRole.getLoginTime());
			detail.setPayTime(wanRechargeOrder == null ? null : wanRechargeOrder.getPaytime());
			detail.setRegtime(wanUser == null ? null : wanUser.getRegtime());
			detail.setRoleLevel(gameRole == null ? null : gameRole.getRoleLevel());
			detail.setTotalRechargeAmount(hbActivityRoleInfo == null ? null : hbActivityRoleInfo.getTotalRechargeAmount());
			return R.ok(detail);
		} catch (Exception e) {
			return R.failed("接口异常，请联系管理员");
		}
	}
}


